﻿package binarytree;

import java.util.LinkedList;
import java.util.Queue;

import common.BTNode;

public class 按层打印二叉树 {

	public void printByLevel(BTNode root) {
		if (root == null) {
			return;
		}
		Queue<BTNode> queue = new LinkedList<>();
		int level = 1;
		BTNode last = root;
		BTNode nLast = null;
		queue.offer(root);
		System.out.println("Level " + (level++) + " : ");
		while (!queue.isEmpty()) {
			root = queue.poll();
			System.out.println(root.value + " ");
			if (root.left != null) {
				queue.offer(root.left);
				nLast = root.left;
			}
			if (root.right != null) {
				queue.offer(root.right);
				nLast = root.right;
			}
			if (root == last && !queue.isEmpty()) {
				System.out.println("\nLevel " + (level++) + " : ");
				last = nLast;
			}
		}
		System.out.println();
	}
}
